package com.zkadmin.renderer;

import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;

import com.zkadmin.controller.EditResourceTreeDialogCtrl;
import com.zkadmin.entity.SysResource;
import com.zkadmin.service.SysResourceService;
import com.zkadmin.util.AdminConstants;
import com.zkadmin.util.MsgBox;

public class EditResourceTreeListRenderer extends BaseRenderer implements ListitemRenderer<SysResource> {
	private SysResourceService sysResourceService;
	private EditResourceTreeDialogCtrl editResourceTreeDialogCtrl;

	public EditResourceTreeListRenderer(Window win, EditResourceTreeDialogCtrl editResourceTreeDialogCtrl, SysResourceService sysResourceService) {
		this.sysResourceService = sysResourceService;
		this.editResourceTreeDialogCtrl = editResourceTreeDialogCtrl;
	}

	@Override
	public void render(Listitem listitem, final SysResource menu, int index) throws Exception {
		final Textbox nameBox = new Textbox(menu.getName());
		nameBox.setInplace(true);
		nameBox.setWidth("90%");
		nameBox.setMaxlength(20);
		nameBox.setParent(createListcell(listitem));
		nameBox.setConstraint("no empty");
		nameBox.addEventListener(Events.ON_CHANGE, new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {
				menu.setName(nameBox.getText());
				saveAndRefresh(menu);
			}
		});

		final Textbox codeBox = new Textbox(menu.getCode());
		codeBox.setInplace(true);
		codeBox.setWidth("90%");
		codeBox.setMaxlength(12);
		codeBox.setConstraint("no empty,/([1-9]\\d)(\\d\\d)*/:填写偶数位数字");
		codeBox.setParent(createListcell(listitem));
		codeBox.addEventListener(Events.ON_CHANGE, new EventListener<Event>() {
			@Override
			public void onEvent(Event event) throws Exception {
				String newCode = codeBox.getValue();
				int len = newCode.length();
				if (len <= 0) {
					throw new WrongValueException(codeBox, "代码不能为空");
				}

				if (len % 2 != 0) {
					throw new WrongValueException(codeBox, "代码必须是偶数位");
				}

				SysResource existMenu = sysResourceService.findByCode(newCode);
				if (existMenu != null && existMenu.getId() != menu.getId()) {
					throw new WrongValueException(codeBox, "代码已经存在");
				}

				menu.setCode(newCode);
				saveAndRefresh(menu);
			}

		});
	}

	private void saveAndRefresh(final SysResource role) {
		try {
			sysResourceService.save(role);
		} catch (ObjectOptimisticLockingFailureException e) {
			MsgBox.alert(AdminConstants.getErrorDataVersionMessage());
		} finally {
			editResourceTreeDialogCtrl.refreshData();
		}
	}
}
